<!--  -->
<template>
  <div class="app-container">
    <input
      id="imFile"
      type="file"
      style="display: none"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      @change="importFile(this)"
    >
    <el-button type="primary" @click="uploadFile">导入</el-button>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <template v-for="(item,index) in activeList">
        <el-tab-pane :key="index" :label="item.head" :name="item.head">
          <el-button @click="handleSet(item.head)">表格数据加工</el-button>
          <el-table
            :data="item.values"
            style="width: 100%"
            @header-click="headerClick(...arguments,index)"
          >
            <template v-for="(item2, index2) in item.keys">
              <el-table-column
                :key="index2"
                :prop="item2"
                :label="item2"
              >
                <template slot="header">
                  <div @click="clickBox" @change="changeBox">
                    <span style="margin-right:10px;">
                      {{ item2 }}
                      <!-- @change="clickBox" -->
                      <el-checkbox />
                    </span>
                  </div>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-tab-pane>
      </template>
    </el-tabs>

    <!-- 数据加工 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- <div class="demo-input-suffix">
        属性方式：
        <el-input
          v-model="input2"
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
        />
      </div> -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-table
          v-if="activeList[activeIndex] && activeList[activeIndex].activeForm"
          :data="activeList[activeIndex].activeForm"
          style="width: 100%"
        >
          <el-table-column
            label="已选表头"
            width="180"
          >
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.head }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="处理数据类型"
            width="120"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.type" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="数据处理结果值"
            width="120"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.field" placeholder="请输入结果" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addXlsx } from '@/api/xlsx/param'
import XLSX from 'xlsx'
import dayjs from 'dayjs'

export default {
  name: 'Index',
  data() {
    return {
      fullscreenLoading: false, // 加载中
      imFile: '', // 导入文件el
      errorMsg: '', // 错误信息内容
      activeList: [],
      activeName: 'second', // tab选择内容
      // 当前在操作的数组下标
      activeIndex: 0,
      dataXlsx: [],
      // 是否显示弹出层
      open: false,
      // 展示名
      title: null,
      // 表单参数
      form: {
        roleName: ''
      },
      // 表单校验
      rules: {

      },
      // 数据库类型下拉
      options: [{
        value: 'String',
        label: 'String'
      }, {
        value: 'Int',
        label: 'Int'
      }, {
        value: 'Double',
        label: 'Double'
      }, {
        value: 'Date',
        label: 'Date'
      }]
    }
  },
  mounted() {
    this.imFile = document.getElementById('imFile')
  },
  methods: {
    handleClick(tab, event) {
      this.activeIndex = tab.index
      console.log(tab, event)
    },
    uploadFile: function() {
      // 点击导入按钮
      this.imFile.click()
    },

    importFile: function() {
      // 导入excel
      this.fullscreenLoading = true
      const obj = this.imFile
      if (!obj.files) {
        this.fullscreenLoading = false
        return
      }
      var f = obj.files[0]
      var reader = new FileReader()
      const $t = this
      reader.onload = (e) => {
        var data = e.target.result
        if ($t.rABS) {
          $t.wb = XLSX.read(btoa(this.fixdata(data)), {
            // 手动转化
            type: 'base64'
          })
        } else {
          $t.wb = XLSX.read(data, {
            type: 'binary'
          })
        }
        // 清空
        this.activeList = []
        // console.log('数量', $t.wb.SheetNames)
        for (const i in $t.wb.SheetNames) {
          this.activeList.push({
            head: $t.wb.SheetNames[i],
            activeData: [],
            activeForm: []
          })
          const json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[i]]).splice(0, 10)
          // console.log('内容', json, json.length)
          $t.dealFile(json, i) // analyzeData: 解析导入数据
        }
        // 设定默认选中
        console.log(this.activeList[0])
        this.activeName = this.activeList[0].head
      }
      if (this.rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    dealFile: function(data, index) {
      // 处理导入的数据
      this.imFile.value = ''
      this.fullscreenLoading = false
      if (data.length <= 0) {
        this.errorMsg = '请导入正确信息'
      } else {
        // 导入成功，处理数据
        let dataIndex = []
        const dataItem = []
        data.forEach(item => {
          dataIndex = Object.keys(item)
          dataItem.push(item)
          // 处理时间
          dataIndex.forEach((item2, index) => {
            if (item2.indexOf('时间') > -1) {
              // console.log(item[dataIndex[index]])
              if (typeof item[dataIndex[index]] === 'number') {
                item[dataIndex[index]] = dayjs('1900-01-01').add(item[dataIndex[index]], 'day').format('YYYY-MM-DD')
              }
            }
          })
          // console.log(item)
          // console.log(dataIndex)
        })
        // 获取对象 下标数组
        this.activeList[index].keys = dataIndex
        // 获取对象 属性数组
        this.activeList[index].values = dataItem
      }
    },

    fixdata: function(data) {
      // 文件流转BinaryString
      var o = ''
      var l = 0
      var w = 10240
      for (; l < data.byteLength / w; ++l) {
        o += String.fromCharCode.apply(
          null,
          new Uint8Array(data.slice(l * w, l * w + w))
        )
      }
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
      return o
    },
    // 多选点击事件
    clickBox(e) {
      // console.log(e.path[0].lastChild)
      if (e.path[0].lastChild && e.path[0].lastChild.click) {
        e.path[0].lastChild.click()
      }
    },
    // 多选修改事件
    changeBox(e) {
      // console.log(e.path[4])
      if (e.path[4].click) {
        e.path[4].click()
      }
    },
    // 设置行
    headerClick(column, event, listIndex) {
      // .childNodes[0].childNodes[0]
      if (event.path[0] && event.path[0].childNodes[0] && event.path[0].childNodes[0].childNodes[0] && event.path[0].childNodes[0].childNodes[0].childNodes[0] && event.path[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].click) {
        event.path[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].click()
      }
      const className = column.id
      const data = document.getElementsByClassName(className)
      this.activeIndex = listIndex
      // 只取第一行，则表头
      data.forEach((item, index) => {
        // let selectClass = document.getElementsByClassName(className)[0]
        // 两次点击取消样式
        if (!item.style.color) {
          // 对编辑表格添加选中项
          item.style.color = '#409EFF'
        } else {
          item.style.color = null
        }
      })
      // 选中表头
      const num = this.activeList[listIndex].activeData.indexOf(column.label)
      if (num >= 0) {
        this.activeList[listIndex].activeData.splice(num, 1)
        this.activeList[listIndex].activeForm.splice(num, 1)
      } else {
        this.activeList[listIndex].activeData.push(column.label)
        this.activeList[listIndex].activeForm.push({
          head: column.label,
          type: null,
          field: null
        })
      }
    },
    // xlsx时间转换
    formatDate(numb, format = '-') {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    // 表格数据加工
    handleSet(head) {
      this.title = head
      this.open = true
    },
    // 取消按钮
    cancel() {
      this.open = false
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        const data = {
          etlTaskMappingList: this.activeList[this.activeIndex].activeForm,
          modulesName: this.title
        }
        addXlsx(data).then(response => {
          if (response.code === 200) {
            this.msgSuccess('添加成功')
            this.open = false
          }
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>

</style>
